package com.example.zhihuijiaju;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UdpClientThread extends Thread {

    //IP地址
    private String mAddress;
    //端口
    private int port;
    //发送内容
    private String msg;
    private Handler mHandler;

    public UdpClientThread(Handler handler, String address, int port, String msg) {
        this.mHandler = handler;
        this.mAddress = address;
        this.port = port;
        this.msg = msg;
    }

    @Override
    public void run() {
        super.run();
        sendSocket();
    }

    /**
     * 设置
     */
    private void sendSocket() {
        byte[] bytes = msg.getBytes();
        try {
            /*******************发送数据***********************/
            InetAddress address = InetAddress.getByName(mAddress);
            //1.构造数据包
            DatagramPacket packet = new DatagramPacket(bytes,
                    bytes.length, address, port);
            //2.创建数据报套接字并将其绑定到本地主机上的指定端口。
            DatagramSocket socket = new DatagramSocket(null);
            socket.bind(new InetSocketAddress(Integer.parseInt("8266")));
            //3.从此套接字发送数据报包。
            Log.i("udp","发送数据...");
            socket.send(packet);
            /*******************接收数据***********************/
            while(true){
                //1.构造 DatagramPacket，用来接收长度为 length 的数据包。
                final byte[] bytes1 = new byte[1024];

                DatagramPacket receiverPacket = new DatagramPacket(bytes1, bytes1.length);
                //超时6s
                try {
                    socket.setSoTimeout(10000);
                    socket.receive(receiverPacket);
                    sendMsg(0,new String(bytes1, 0, bytes1.length));
                } catch (IOException e) {
                    e.printStackTrace();
                    sendMsg(0,new String("{\"code\":\"-1\"}"));
                    break;
                }


            }
            socket.close();

           // socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息系统
     */
    private void sendMsg(int what, Object object) {
        Message msg = new Message();
        msg.what = what;
        msg.obj = object;
        mHandler.sendMessage(msg);
    }
}

